import Food from "./Food";


export default class Snake {
  // 蛇的容器
  el: HTMLElement = document.querySelector("#snake") as HTMLElement;
  // 蛇的身体
  els: NodeListOf<HTMLElement> = document.querySelectorAll("#snake > div");
  // 缓存一下蛇尾部的坐标，在吃到食物时作为新蛇尾的初始化坐标
  footer: {x: number, y: number} = {x: 0, y: 0}
  // 移动方向
  direction: string = "ArrowRight";
  // 是否存活
  isLife: boolean = true;
  constructor() {

  }
  // 设置蛇头坐标
  get X(): number {
    return this.els[0].offsetLeft;
  }
  set X(val) {
    this.els[0].style.left = val + "px";
  }
  get Y(): number {
    return this.els[0].offsetTop;
  }
  set Y(val) {    
    this.els[0].style.top = val + "px";
  }

  // 移动
  run(): void {
    // 缓存一下蛇尾部的坐标，在吃到食物时作为新蛇尾的初始化坐标
    this.footer.x = this.els[this.els.length - 1].offsetLeft;
    this.footer.y = this.els[this.els.length - 1].offsetTop;

    for (let i = this.els.length - 1; i >= 0; i--) {
      // 如果是蛇头，则根据this.direction来使蛇的位置改变
      // 否则根据前一个蛇的身体来更新坐标
      if (i == 0) {
        switch(this.direction) {
          case "ArrowUp":
            this.Y -= 10;
            break;
          case "ArrowDown":
            this.Y += 10;
            break;
          case "ArrowLeft":
            this.X -= 10;
            break;
          case "ArrowRight":
            this.X += 10;
            break;
        }
      } else {
        this.els[i].style.left = this.els[i - 1].offsetLeft + "px";
        this.els[i].style.top = this.els[i - 1].offsetTop + "px";
      }
    }

    if (this.isHitWall() || this.isHitSelf() || this.els.length == 30 ** 2) {
      this.isLife = false;
    }


  }
  // 是否撞墙
  isHitWall(): boolean {
    return this.X < 0 || this.X > 290 || this.Y < 0 || this.Y > 290;
  }
  // 是否撞到自己
  isHitSelf(): boolean {
    for (let i = 1; i < this.els.length; i++) {
      if (this.X == this.els[i].offsetLeft && this.Y == this.els[i].offsetTop) return true;
    }
    return false;
  }

  // 吃食物
  eat(food: Food): boolean {
    // 没吃到
    if (this.X != food.X || this.Y != food.Y) return false;

    // 吃到了，添加蛇的身体，更新食物位置
    food.change(this);
    this.add();
    return true;

  }

  // 添加蛇的身体
  add(): void {
    let div: HTMLElement = document.createElement("div");
    div.style.left = this.footer.x + "px";
    div.style.top = this.footer.y + "px";
    this.el.append(div);
    this.els = document.querySelectorAll("#snake > div");
  }
}